<template>
    <div class="page">
        <div class="centered-container">
            <div class="form-container">
                <form @submit.prevent="fetchAroundHotels">
                    <div class="input-group">
                        <label for="checkin">入住日期：</label>
                        <input type="date" v-model="checkin" @change="checkDates" required>
                    </div>
                    <div class="input-group">
                        <label for="checkout">离店日期：</label>
                        <input type="date" v-model="checkout" @change="checkDates" required>
                    </div>
                    <div class="input-group">
                        <label for="guests">人数：</label>
                        <input type="number" v-model="guests" min="1" required>
                    </div>
                    <div class="takeup"/>
                    <div class="input-group">
                        <label for="city">所在省份: </label>
                        <select v-model="selectedProvince" @change="fetchCities">
                            <option v-for="(province, index) in provinces" :key="index" :value="province">{{
                                province.name }}</option>
                        </select>
                    </div>
                    <div class="input-group">
                        <label for="city">所在城市: </label>
                        <select v-model="selectedCity" @change="fetchDistricts">
                            <option v-for="(city, index) in cities" :key="index" :value="city">{{ city.name }}</option>
                        </select>
                    </div>
                    <div class="input-group">
                        <label for="region">所在区域: </label>
                        <select v-model="selectedDistrict">
                            <option v-for="(district, index) in districts" :key="index" :value="district">{{
                                district.name }}</option>
                        </select>
                    </div>
                    <div class="input-group">
                        <label for="hotelType">酒店类型: </label>
                        <select v-model="selectedHotelType">
                            <option value="100100">宾馆酒店</option>
                            <option value="100101">奢华酒店</option>
                            <option value="100102">五星级宾馆</option>
                            <option value="100103">四星级宾馆</option>
                            <option value="100104">三星级宾馆</option>
                            <option value="100105">经济型连锁酒店</option>
                            <option value="100200">旅馆招待所</option>
                            <option value="100201">青年旅舍</option>
                        </select>
                    </div>

                    <div class="input-group">
                        <button class="btn sort-btn" type="button" @click="sortByRating">评分</button>
                        <button class="btn sort-btn" type="button" @click="sortByDistance">距离</button>
                    </div>
                    <div>
                        <input type="submit" class="btn" value="查询">
                    </div>
                </form>
            </div>
        </div>
        <div class="container" style="align-items: stretch">
            <div class="content">
                <h2>酒店列表</h2>
                <div v-if="hotels" v-for="hotel in paginatedHotels" :key="hotel.id" class="hotel"
                    @click="navigateToHotelDetail(hotel)">
                    <div class="hotel-img">
                        <el-carousel indicator-position="outside" height="150px">
                            <el-carousel-item v-for="(photo, index) in getPhotos(hotel)" :key="index">
                                <div @click="manualSwitch(hotel, index)"
                                    :style="{ 'background-image': 'url(' + photo.url + ')', width: '150px', height: '150px', 'background-size': 'cover' }">
                                </div>
                            </el-carousel-item>
                        </el-carousel>
                    </div>
                    <div class="hotel-info">
                        <h2>{{ hotel.name }}</h2>
                        <p>评分：{{ hotel.biz_ext && hotel.biz_ext.rating ? hotel.biz_ext.rating : '暂无' }}</p>
                        <p>位置：{{ hotel.address ? hotel.address : '地址迁移' }}</p>
                        <p>距离：{{ hotel.distance ? `${hotel.distance} 米` : '暂无参考' }}</p>
                    </div>
                </div>
                <div class="custom-pagination">
                    <el-pagination @current-change="currentPage = $event" :current-page="currentPage"
                        :page-size="perPage" :page-sizes="[3]"
                        @size-change="perPage = $event; currentPage = 1; fetchAroundHotels()"
                        layout="total, sizes, prev, pager, next, jumper" :total="totalPages * perPage">
                    </el-pagination>
                </div>
            </div>
            <div class="map">
                <AroundMap :location="currentLocation" :marksPosition="positions"></AroundMap>
            </div>
        </div>

    </div>
</template>

<script>
import AroundMap from "./around-map-component.vue";
import api from '@/api';
import axios from 'axios';
import { MessageBox } from 'element-ui';


export default {
    name: "around-hotels",
    components: {
        AroundMap,
    },
    data() {
        const currentDateStr = this.getCurrentDate();
        // 将当前日期字符串转换为日期对象
        const currentDate = new Date(currentDateStr);
        const tomorrowDate = new Date(currentDate);
        tomorrowDate.setDate(currentDate.getDate() + 1);
        // 将明天的日期转换为字符串
        const tomorrowDateStr = tomorrowDate.toISOString().split('T')[0];
        return {
            currentDateStr: currentDateStr,
            tomorrowDateStr: tomorrowDateStr,
            checkin: currentDateStr,
            checkout: tomorrowDateStr,
            provinces: [],
            cities: [],
            districts: [],
            selectedProvince: {},
            selectedCity: {},
            selectedDistrict: {},
            guests: 1,
            currentPage: 1,
            perPage: 3,
            hotels: [],
            intervalIds: {}, // 记录所有酒店的照片轮播间隔ID
            currentPhotoIndex: {}, // 记录每个酒店的当前照片索引
            selectedHotelType: "100100",
        };
    },
    computed: {
        positions() {
            return this.hotels.map(hotel => {
                const locationArray = hotel.location.split(',').map(parseFloat);
                return locationArray;
            });
        },
        currentLocation() {
            if (this.hotels.length > 0) {
                return this.hotels[0].location.split(',').map(Number);
            }
            return [103.897928, 30.794929]; // hotels 数组为空的情况
        },
        paginatedHotels() {
            const start = (this.currentPage - 1) * this.perPage;
            const end = this.currentPage * this.perPage;
            return this.hotels.slice(start, end);
        },
        totalPages() {
            return Math.ceil(this.hotels.length / this.perPage);
        },
        currentPhoto() {
            return hotel => {
                const currentIndex = this.currentPhotoIndex[hotel.address];
                if (currentIndex !== undefined && hotel.photos && hotel.photos.length > 0) {
                    return hotel.photos[currentIndex];
                } else {
                    return { url: 'https://via.placeholder.com/150' };
                }
            };
        }
    },
    mounted() {
        this.fetchAroundHotels();
        this.fetchProvinces();
    },
    methods: {
        // 导航到酒店详情页
        navigateToHotelDetail(hotel) {
            this.$router.push({
                name: 'IndexHotelDetail',
                query: {
                    hotel: JSON.stringify(hotel),
                    checkin: this.checkin,
                    checkout: this.checkout
                }
            });
        },
        getCurrentDate() {
            let today = new Date();
            let month = String(today.getMonth() + 1).padStart(2, '0');
            let day = String(today.getDate()).padStart(2, '0');
            let year = today.getFullYear();
            return `${year}-${month}-${day}`;
        },
        checkDates() {
            // 获取入住日期和离开日期的时间戳
            const checkinTimestamp = new Date(this.checkin).getTime();
            const checkoutTimestamp = new Date(this.checkout).getTime();
            // 校验离开日期不能小于入住日期
            if (checkoutTimestamp < checkinTimestamp) {
                this.checkin = this.currentDateStr;
                this.checkout = this.tomorrowDateStr; // 重置离开日期

                MessageBox.alert('离店日期不能小于入住日期，请重新选择日期。', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                });
            } else if (checkinTimestamp < new Date().setHours(0, 0, 0, 0)) {
                this.checkin = this.currentDateStr; // 重置入住日期为今天
                MessageBox.alert('入住日期无效，请重新选择日期。', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning'
                });
            }
        },
        getPhotos(hotel) {
            if (hotel.photos && hotel.photos.length > 0) {
                return hotel.photos;
            } else {
                return [{ url: 'https://via.placeholder.com/150' }];
            }
        },
        // 为酒店设置照片轮播
        fetchPhotos(hotel) {
            if (!hotel.photos || hotel.photos.length === 0) return;

            // 初始化每个酒店项的 currentIndex
            this.$set(this.currentPhotoIndex, hotel.address, 0);
            // 设置照片轮播间隔
            this.$set(this.intervalIds, hotel.address, setInterval(() => {
                this.nextPhoto(hotel);
            }, 5000));
        },
        nextPhoto(hotel) {
            const currentIndex = this.currentPhotoIndex[hotel.address];
            if (currentIndex !== undefined && hotel.photos) {
                this.currentPhotoIndex[hotel.address] = (currentIndex + 1) % hotel.photos.length;
            }
        },
        // 获取周边酒店数据
        fetchAroundHotels() {
            console.log(this.selectedProvince.name + ' ' + this.selectedCity.name + ' ' + this.selectedDistrict.name);
            // console.log(api.searchHotels.aroundHotels);
            this.$get(api.searchHotels.aroundHotels, { types: this.selectedHotelType, province: this.selectedProvince.name, city: this.selectedCity.name, region: this.selectedDistrict.name })
                .then((response) => {
                    console.log("周边酒店数据:", response);
                    // 处理后端返回的数据转换为适合前端使用的格式
                    const hotels = response.map((item) => ({
                        id: item.id || '',
                        name: item.name || '',
                        address: item.address || '',
                        location: item.location || [],
                        distance: item.distance || '',
                        pname: item.pname || '',
                        importance: item.importance || [],
                        biz_ext: {
                            cost: item.biz_ext.cost || [],
                            star: item.biz_ext.star || [],
                            opentime2: item.biz_ext.opentime2 || [],
                            rating: parseFloat(item.biz_ext.rating) || 0,
                            lowest_price: item.biz_ext.lowest_price || [],
                            hotel_ordering: item.biz_ext.hotel_ordering || '',
                            open_time: item.biz_ext.open_time || [],
                            meal_ordering: item.biz_ext.meal_ordering || ''
                        },
                        biz_type: item.biz_type || '',
                        cityname: item.cityname || '',
                        type: item.type || '',
                        photos: item.photos.map(photo => ({
                            title: photo.title || '',
                            url: photo.url || ''
                        })) || [],
                    }));

                    // 将转换后的数据赋值给组件的 hotels 属性
                    this.hotels = hotels;
                    localStorage.setItem("hotels", JSON.stringify(hotels));
                    // console.log("local Hotels: " + localStorage.getItem('hotels'));

                    // 调用fetchPhotos方法加载照片数据
                    this.hotels.forEach(item => {
                        this.fetchPhotos(item);
                    });
                })
                .catch((error) => {
                    console.error("获取周边酒店数据失败:", error);
                });
        },
        sortByRating() {
            // 清除现有的定时器
            Object.keys(this.intervalIds).forEach(key => {
                clearInterval(this.intervalIds[key]);
            });
            this.intervalIds = {};

            // 排序酒店列表
            const sortedHotels = [...this.hotels].sort((a, b) => {
                const ratingA = a.biz_ext && a.biz_ext.rating ? a.biz_ext.rating : 0;
                const ratingB = b.biz_ext && b.biz_ext.rating ? b.biz_ext.rating : 0;
                return ratingB - ratingA; // 降序排列
            });

            this.hotels = sortedHotels;
            this.currentPage = 1; // 排序后回到第一页

            // 重新初始化照片轮播
            this.hotels.forEach(hotel => {
                this.fetchPhotos(hotel);
            });
        },
        sortByDistance() {
            // 清除现有的定时器
            Object.keys(this.intervalIds).forEach(key => {
                clearInterval(this.intervalIds[key]);
            });
            this.intervalIds = {};

            // 排序酒店列表
            const sortedHotels = [...this.hotels].sort((a, b) => {
                const distanceA = a.distance ? parseFloat(a.distance) : Infinity;
                const distanceB = b.distance ? parseFloat(b.distance) : Infinity;
                return distanceA - distanceB; // 升序排列
            });

            this.hotels = sortedHotels;
            this.currentPage = 1; // 排序后回到第一页

            // 重新初始化照片轮播
            this.hotels.forEach(hotel => {
                this.fetchPhotos(hotel);
            });
        },
        // 获取省份数据
        async fetchProvinces() {
            const key = '3d6a7f5c57d9427752c77bfd64a1b14d';
            try {
                const response = await axios.get(`https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=1&key=${key}`);
                this.provinces = response.data.districts[0].districts;
                this.selectedProvince = this.provinces[4];
                this.fetchCities();
            } catch (error) {
                console.error(error);
            }
        },
        // 根据选中的省份获取城市数据
        async fetchCities() {
            const key = '3d6a7f5c57d9427752c77bfd64a1b14d';
            try {
                if (this.isSpecialRegion(this.selectedProvince.name)) {
                    this.selectedCity = '';
                } else {
                    const response = await axios.get(`https://restapi.amap.com/v3/config/district?keywords=${this.selectedProvince.name}&subdistrict=1&key=${key}`);

                    console.log(this.selectedProvince + this.selectedCity + this.selectedDistrict);
                    this.cities = response.data.districts[0].districts;
                    this.selectedCity = this.cities[22];
                }
                this.fetchDistricts();
            } catch (error) {
                console.error(error);
            }
        },
        // 根据选中的城市获取区域数据
        async fetchDistricts() {
            const key = '3d6a7f5c57d9427752c77bfd64a1b14d';
            try {
                if (this.isSpecialRegion(this.selectedProvince.name)) {
                    this.selectedDistrict = '';
                } else {
                    const response = await axios.get(`https://restapi.amap.com/v3/config/district?keywords=${this.selectedCity.name}&subdistrict=1&key=${key}`);
                    console.log(`fetchDistricts: ${response}`);
                    this.districts = response.data.districts[0].districts;
                    this.selectedDistrict = this.districts[3];
                }
            } catch (error) {
                console.error(error);
            }
        },
        isSpecialRegion(name) {
            // 判断是否是台湾、香港或澳门
            return name === '台湾省' || name === '香港特别行政区' || name === '澳门特别行政区';
        },
    },
    beforeDestroy() {
        // 清除所有的定时器
        Object.keys(this.intervalIds).forEach(key => {
            clearInterval(this.intervalIds[key]);
        });
    }
};
</script>

<style scoped lang="scss">
.page {
    display: flex;
    flex-direction: column;
    align-items: center;

    .centered-container {
        width: 100%;
        max-width: 1200px;
        padding: 0 20px;
    }

    .form-container {
        background-color: #fff;
        padding: 20px;
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        border-radius: 8px;
        margin-bottom: 20px;

        form {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
        }

        .input-group {
            margin-bottom: 15px;
            display: flex;
            align-items: center;

            .sort-btn {
                margin-left: 10px;
            }

            label {
                margin-right: 10px;
            }

            input,
            select {
                flex: 1;
                padding: 8px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 14px;
                height: 36px;
            }

            input[type="date"] {
                min-width: 200px;
            }

            input[type="number"] {
                width: 100px;
            }
        }
    }

    .container {
        width: 100%;
        max-width: 1200px;
        display: flex;
        justify-content: space-between;
        margin-top: 20px;

        .content {
            flex: 2;
            /* 酒店列表占比较大的宽度 */
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            margin-right: 20px;

            .hotel {
                margin-bottom: 20px;
                padding: 10px;
                border: 1px solid #ddd;
                border-radius: 5px;
                display: flex;
                align-items: center;
                transition: box-shadow 0.3s;

                &:hover {
                    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
                    cursor: pointer;
                }

                .hotel-img {
                    width: 150px;
                    height: 150px;
                    overflow: hidden;
                    border-radius: 5px;

                    img {
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                    }

                }

                .hotel-info {
                    flex: 1;
                    padding-left: 20px;

                    h2 {
                        margin-top: 0;
                        font-size: 20px;
                        text-align: left;
                    }

                    p {
                        margin: 5px 0;
                        color: #555;
                    }
                }
            }

            .pagination {
                margin-top: 20px;
                display: flex;
                justify-content: center;

                button {
                    margin: 0 5px;
                    padding: 10px 20px;
                    border: 1px solid #ddd;
                    background-color: #fff;
                    cursor: pointer;
                    transition: background-color 0.3s, color 0.3s;

                    &.active,
                    &:hover {
                        background-color: #007bff;
                        color: #fff;
                        border: none;
                    }
                }
            }
        }

        .map {
            flex: 1;
            height: auto;
            background-color: #e0e0e0;
            border-radius: 8px;
            overflow: hidden;

            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
            }
        }
    }
}
</style>
